﻿#region Disclaimer / License
// Copyright (C) 2011, Kenneth Bergeron, IAP Worldwide Services, Inc
// NOAA :: National Marine Fisheries Service
// 
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// 
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
// 
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
// 
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace CatchProcessing
{
    /// <summary>
    /// Catch Processing MAIN program
    /// </summary>
    static class Program
    {
        // Me name
        public const string Name = "CatchProcessing";
        // Me home
        public static string ApplicationDataDirectory { get; private set; }
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            // Only allow one of me by locking a mutex
            bool SingleInstance = false;
            using (System.Threading.Mutex Single = new System.Threading.Mutex(true, Name, out SingleInstance))
            {
                if (!SingleInstance)
                {
                    MessageBox.Show("Catch Processing is already running.");
                    Environment.Exit(-1);
                    return;
                }
#if !DEBUG
                try
#endif
                {
                    // Use the EASA directory
                    ApplicationDataDirectory = DataSets.Glob.EASADataFolder;
                    // Test the data folder
                    Exception TestEx = DataSets.Glob.TestAppDataFolder(ApplicationDataDirectory);
                    if (TestEx != null)
                    {
                        MessageBox.Show("Error accessing " + ApplicationDataDirectory + ": " + TestEx.Message);
                        Environment.Exit(-1);
                        return;
                    }
                    // Load the global support database
                    Exception[] Exs = DataSets.Glob.LoadSupport(Name, ApplicationDataDirectory);
                    // Find the database
                    string Cruise;
                    string VesselCode;
                    DataSets.Glob.EASADatabase = DataSets.Glob.GetVesselCruise(out VesselCode, out Cruise);
                    Properties.Settings.Default.VesselCode = VesselCode;
                    Properties.Settings.Default.Cruise = Cruise;
                    if (string.IsNullOrEmpty(DataSets.Glob.EASADatabase))
                    {
                        MessageBox.Show("EASA Database is not installed in " + DataSets.Glob.EASADataFolder +
                            ".\nThis must be installed before CatchProcessing may be run.",
                            "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        Environment.Exit(-1);
                        return;
                    }
                    if( Exs != null && Exs.Length > 0)
                    {
                        MessageBox.Show("The Support database, " + DataSets.EASASettingsDataSet.DefaultXMLFile + ", can not be loaded\n" +
                            string.Join("\n", Exs.Select(qM=>qM.Message)) + "\nReinstalling the application may correct this.");
                        Environment.Exit(-1);
                        return;
                    }
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new CatchProcessing());
                    Environment.Exit(0);
                }
#if !DEBUG
                catch (Exception Ex)
                {
                    Console.WriteLine(Ex.Message);
                    MessageBox.Show(Ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Environment.Exit(-1);
                }
#endif
            } // using
        } // main
        /// <summary>
        /// Well, it's inevitable, Here I look for the 'anywhere in the world' 
        /// folder in the good-ole ini file (sigh)
        /// </summary>
        /// <remarks>
        /// The INI file is created at installation.
        /// Expects "InstallPath=C:\WackoCommonAppsDir" to be the first line in the INI file.
        /// </remarks>
        /// <returns>Default sane people's common app dir or morphidic one form INI file.</returns>
        private static string GetCommonAppDir()
        {
            string Result = Properties.Settings.Default.CommonAppDirectory;
            // If set in properties, this has already beed done, no need to repeat it
            if (!string.IsNullOrEmpty(Result)) return Result;
            // Default to normal folder
            // Check if identified
            Result = Application.CommonAppDataPath;
            if (!Result.Contains(Name))
                Result = System.IO.Path.Combine(Application.CommonAppDataPath, Name);
            string IniFile = System.IO.Path.Combine(Application.StartupPath, Name + ".ini");
            // There is no ini file, oh well...
            if (!System.IO.File.Exists(IniFile)) return Result;
            // Read the INI file.
            try 
	        {
                string[] Parts = System.IO.File.ReadAllText(IniFile).Split('=');
                if (Parts.Length > 1 && Parts[0].Contains("InstallPath"))
                    Result = Parts[1].Replace("\r\n",string.Empty);
                // We're not gonna have permissions for this, but try anyway...
                System.IO.File.Delete(IniFile); // That felt good.  We are done with that one.
	        }
	        catch
	        {
	        }
            return Result;
        }
        // Just for testing...
        public static void UnPost()
        {
            DataSets.EASADataSet sd = new DataSets.EASADataSet();
            DataSets.Glob.LoadSDES(@"C:\EASA_Database\TestData\CR811104-EASA-Populated.mdb", sd);
            DataSets.LocalDataSet lds = new DataSets.LocalDataSet();
            DataSets.PostFish.UnPost(sd, lds);
            lds.Save();
        }
    }
}
//FISH ICON by Turbomilk
//License: Free for commercial use (Include link to this page: http://graphicriver.net/free-icons)
//SEARCH ICON Designer Visual-Blast Magazine
//License: Free for commercial use (Do not redistribute) | (Read me)